<?php

namespace app\beautiful\controller\admin\mall;

use app\BaseController;

use app\beautiful\model\mall\FlashSaleGoodsModel;
use app\beautiful\model\mall\PinTuanGoodsModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\order\PinTuanOrderModel;
use app\common\logic\DataLogic;

use app\common\logic\SmsLogic;

use app\beautiful\logic\printer\PrinterLogic;

use app\beautiful\model\member\MemberModel;

use app\beautiful\model\order\GoodsOrderItemModel;

use app\beautiful\model\order\GoodsOrderModel;

use app\beautiful\model\setting\SettingSmsModel;
use app\stores\model\member\MemberLevelModel;
use think\facade\Db;


class Order extends BaseController{

    public function getGoodsOrderNum()

    {

        $order_num=GoodsOrderModel::where([

                ['shop_id','=',$this->request->shopId],

                ['is_delete','=',0],

                ['status','in',[2,4,9]]

            ])->count() ?? 0;

        return $this->success(['order_num'=>$order_num]);

    }

    /**
     * @return \think\response\Json
     *  {order_id: 3, shop_id: 1, order_type: "normal", logistics_type: 2, member_id: 2, pin_tuan_group_id: 0,…}
    order_id: 3
    shop_id: 1
    order_type: "normal"
    logistics_type: 2
    member_id: 2
    pin_tuan_group_id: 0
    total_price: "374.00"
    need_pay: "374.00"
    freight: "0.00"
    member_coupon_id: 0
    coupon_money: "0.00"
    use_integral: 0
    integral_balance: "0.00"
    youhui_balance: "0.00"
    pay_type: null
    is_paid: 0
    status: 1
    is_delete: 0
    pay_time: 0
    pay_info: null
    receiving_name: null
    receiving_mobile: null
    receiving_address_province: null
    receiving_address_city: null
    receiving_address_county: null
    receiving_address_info: null
    add_time: 1637815112
    add_ip: "120.36.171.132"
    skus: [{order_item_id: 3, shop_id: 1, order_id: 3, goods_type: "normal", goods_id: 1,…},…]
    0: {order_item_id: 3, shop_id: 1, order_id: 3, goods_type: "normal", goods_id: 1,…}
    order_item_id: 3
    shop_id: 1
    order_id: 3
    goods_type: "normal"
    goods_id: 1
    goods_name: "如玉研奢华莹肌水润修复面膜"
    goods_cover_img: "https://img.meichengkj.com/316ebdeb1333a685b1cef397fcdc79011637811118.png"
    goods_sku_id: 0
    goods_sku_name: ""
    goods_original_price: "68.00"
    yu_days: 0
    group_size: 0
    goods_price: "66.00"
    goods_num: 3
    add_time: 1637815112
    add_ip: "120.36.171.132"
    sku{0:{order_item_id: 3, shop_id: 1, order_id: 3, goods_type: "normal", goods_id: 1,…}
    order_item_id: 3
    shop_id: 1
    order_id: 3
    goods_type: "normal"
    goods_id: 1
    goods_name: "如玉研奢华莹肌水润修复面膜"
    goods_cover_img: "https://img.meichengkj.com/316ebdeb1333a685b1cef397fcdc79011637811118.png"
    goods_sku_id: 0
    goods_sku_name: ""
    goods_original_price: "68.00"
    yu_days: 0
    group_size: 0
    goods_price: "66.00"
    goods_num: 3
    add_time: 1637815112
    add_ip: "120.36.171.132"
     }
    member: {member_id: 2, shop_id: 1, open_id: "oP9gm5TMeq_UizdgKfA2NZCqvK50", nick_name: "未设置", face: null,…}
    add_time_format: "2021-11-25 12:38:32"
    pay_time_format: "-"
    status_means: "待付款"
    order_type_means: "商品订单"
    pay_type_mean: "-"
    deliver_num: 0
    write_off_num: 0
     */
    public function index()

    {

        $order_id = $this->request->param('order_id/d',0);

        $order_type=$this->request->param('order_type');

        $mobile=$this->request->param('mobile');

        $status=$this->request->param('status/d',0);

        $member_id=$this->request->param('member_id/d',0);


        $where=[

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

        ];


        if($member_id == 0){

            $member_where=[

                ['shop_id','=',$this->request->shopId]

            ];

            if(!empty($mobile)){

                $member_where[]=['mobile','=',$mobile];

            }

            $member_ids= MemberModel::where($member_where)->column('member_id') ?? [];

            $where[]=['member_id','in',$member_ids];

        }else{

            $where[]=['member_id','=',$member_id];

        }

        if(!empty($status)) $where[]=['status','=',$status];


        if(!empty($order_id)) $where[]=['order_id','=',$order_id];

        if(!empty($order_type)) $where[]=['order_type','=',$order_type];

        $order_model=new GoodsOrderModel();

        $order_model=$order_model->with(['skus','member','partnerCommission']);

        $order=['add_time'=>'desc'];

        $field="*";

        $append=['add_time_format','pay_time_format','status_means','order_type_means','pay_type_mean'];

        $return = DataLogic::getDataList($order_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);




        $deliver_num=GoodsOrderModel::where([

                ['shop_id','=',$this->request->shopId],

                ['is_delete','=',0],

                ['logistics_type','=',1],

                ['status','=',2]

            ])->count() ?? 0;


        $write_off_num=GoodsOrderModel::where([

                ['shop_id','=',$this->request->shopId],

                ['is_delete','=',0],

                ['logistics_type','=',2],

                ['status','=',4]

            ])->count() ?? 0;

        $send_city_num=GoodsOrderModel::where([

                ['shop_id','=',$this->request->shopId],

                ['is_delete','=',0],

                ['logistics_type','=',3],

                ['status','=',9]

            ])->count() ?? 0;


        //处理数据
        $lists = $return['list'];

        if(empty(!$lists)){

            $key_start = $this->request->limit * ($this->request->page - 1);
            $key_end = $return['total'];

            foreach ($lists as $k => $list){

                $lists[$k]['show_order_id']= $key_end - ($key_start + $k);

                if($list['order_send_time']) $lists[$k]['order_send_time'] = json_decode($list['order_send_time'],true);
                $commission = 0;
                foreach ($list['partnerCommission'] as $key=>$value){

                    $commission += $value['commission'];
                }
                unset($lists[$k]['partnerCommission']);
                //股东提成
                $lists[$k]['percentage'] = sprintf("%.2f",$commission);
                //商家实收
                $lists[$k]['boss_real_receive'] = sprintf("%.2f",$list['need_pay'] - $list['freight'] - $commission - $list['coupon_money']);
            }
        }


        $return['list']=$lists;


        $return['deliver_num']=$deliver_num;

        $return['write_off_num']=$write_off_num;
        
        $return['send_city_num']=$send_city_num;

        return $this->success($return);



    }



    public function detail()

    {

        $order_id = $this->request->param('order_id/d',0);

        if($order_id==0) return $this->error('订单不存在#1');

        $order_model = new GoodsOrderModel();

        $order_model = $order_model->with(['partnerCommission']);


        if(null === $order = $order_model->where(['order_id'=>$order_id])->json(['order_send_time'],true)->find()) return $this->error('订单不存在#2');

        if($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');

        if($order->is_delete != 0) return $this->error('订单不存在#4');



        if(null === $member = MemberModel::find($order->member_id)) return $this->error('订单不存在#5');

        if($member->shop_id != $this->request->shopId) return $this->error('订单不存在#6');



        $items=GoodsOrderItemModel::where([

            ['shop_id','=',$this->request->shopId],

            ['order_id','=',$order_id]

        ])->select()->toArray();

        if(empty($items)) return $this->error('订单不存在#7');



        $order->append(['add_time_format','pay_time_format','status_means','order_type_means','pay_type_mean']);

        $commission = 0;

        foreach ($order->partnerCommission as $key=>$value){

            $commission += $value['commission'];
        }

        //股东提成
        $percentage = $commission;
        //商家实收
        $boss_real_receive = $order->need_pay - $order->freight - $commission - $order->coupon_money;

        $detail=[

            'order_id'=>$order->order_id,

            'logistics_type'=>$order->logistics_type,

            'add_time_format'=>$order->add_time_format,

            'order_type_means'=>$order->order_type_means,

            'status'=>$order->status,

            'status_means'=>$order->status_means,

            'need_pay'=>$order->need_pay,

            'pay_type'=>$order->pay_type,

            'pay_type_mean'=>$order->pay_type_mean,

            'pay_time_format'=>$order->pay_time_format,

            'receiving_name'=>$order->receiving_name,

            'receiving_mobile'=>$order->receiving_mobile,

            'receiving_address_province'=>$order->receiving_address_province,

            'receiving_address_city'=>$order->receiving_address_city,

            'receiving_address_county'=>$order->receiving_address_county,

            'receiving_address_info'=>$order->receiving_address_info,

            'total_price'=>$order->total_price,

            'youhui_balance'=>$order->youhui_balance,

            'freight'=>$order->freight,

            'coupon_money'=>$order->coupon_money,

            'integral_balance'=>$order->integral_balance,

            'member_name'=>$member->nick_name,

            'member_mobile'=>$member->mobile,

            'items'=>$items,

            'order_send_time'=>$order->order_send_time,

            'percentage'=>sprintf("%.2f",$percentage),

            'boss_real_receive'=>sprintf("%.2f",$boss_real_receive),

        ];



        return $this->success(['detail'=>$detail]);

    }



    public function overGoods(){

        $order_id = $this->request->param('order_id/d',0);

        if($order_id==0) return $this->error('订单不存在#1');

        if(null === $order = GoodsOrderModel::find($order_id)) return $this->error('订单不存在#2');

        if($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');

        if($order->is_delete != 0) return $this->error('订单不存在#4');

        if($order->logistics_type != 1) $this->error('该订单无法完成');

        if($order->status !=3) return $this->error('该订单无法完成');

        Db::startTrans();

        try{
            $order->status=8;
            $order->edit_time=date('Y-m-d H:i:s');
            $order->save();

            //记录
            $r_data['shop_id'] = $this->request->shopId;
            $r_data['status'] = 5;
            $r_data['order_refund_id'] = 0;
            $r_data['operate_id'] = $this->request->accountId;
            add_record(0,$order_id,$r_data);

            Db::commit();

            return $this->success('订单已完成');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
    }



    public function deliverGoods()

    {

        $order_id = $this->request->param('order_id/d',0);

        if($order_id==0) return $this->error('订单不存在#1');

        if(null === $order = GoodsOrderModel::find($order_id)) return $this->error('订单不存在#2');

        if($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');

        if($order->is_delete != 0) return $this->error('订单不存在#4');

        if($order->logistics_type != 1) $this->error('该订单无法发货');

        if($order->status !=2) return $this->error('该订单无法发货');



        if(null === $member = MemberModel::find($order->member_id)) return $this->error('订单不存在#5');

        Db::startTrans();

        try{

            $order->status=3;
            $order->edit_time=date('Y-m-d H:i:s');
            $order->save();

            //记录
            $r_data['shop_id'] = $this->request->shopId;
            $r_data['status'] = 4;
            $r_data['order_refund_id'] = 0;
            $r_data['operate_id'] = $this->request->accountId;
            add_record(0,$order_id,$r_data);

            //其他要补充的

            //发送短信给用户

            try{

                $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();

                if(null !== $sms_setting){



                    if($sms_setting->order_deliver_notice_member==1){

                        $sms_logic= new SmsLogic();

                        $params=[

                            'id'=>(string)$order->order_sn,

                        ];
                        $re = $sms_logic->send($this->request->shopId,[$member->mobile],$params,'orderDeliverNoticeMember');

                    }

                }

            }catch (\Exception $e){



            }

            Db::commit();

            return $this->success('发货成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
    }



    public function writeOff()

    {

        $order_id = $this->request->param('order_id/d',0);

        if($order_id==0) return $this->error('订单不存在#1');

        if(null === $order = GoodsOrderModel::find($order_id)) return $this->error('订单不存在#2');

        if($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');

        if($order->is_delete != 0) return $this->error('订单不存在#4');

        if(!in_array($order->logistics_type,[2,3])) $this->error('该订单无法核销');

        if(!in_array($order->status,[4,9])) return $this->error('该订单无法核销');

        if(null === $member = MemberModel::find($order->member_id)) return $this->error('订单不存在#5');

        Db::startTrans();

        try{
            $order->status=8;
            $order->edit_time=date('Y-m-d H:i:s');
            $order->save();

            //记录
            $r_data['shop_id'] = $this->request->shopId;
            $r_data['status'] = 3;
            $r_data['order_refund_id'] = 0;
            $r_data['operate_id'] = $this->request->accountId;
            add_record(0,$order_id,$r_data);

            //其他要补充的

            //发送短信给用户

            try{

                $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();

                if(null !== $sms_setting){



                    if($sms_setting->order_write_off_notice_member==1){

                        $sms_logic= new SmsLogic();

                        $params=[

                            'id'=>(string)$order_id,

                        ];

                        $sms_logic->send($this->request->shopId,[$member->mobile],$params,'orderWriteOffNoticeMember');

                    }

                }

            }catch (\Exception $e){



            }



            //打印机

            $printer_logic =new PrinterLogic($this->request->shopId);

            $printer_logic->print('orderWriteOff',$order->order_id);

            Db::commit();

            return $this->success('核销成功');


        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }
    }

}

